<template>
    <div class="relative">
        <div class="flex items-center justify-center">
            <div 
                v-for="(item, index) in menuItemsToUse" 
                :key="index"
                class="flex flex-col items-center gap-2 px-2 py-2 hover:bg-neutral-600 rounded cursor-pointer" 
                @click.stop="handleItemClick(item, index)"
            >
                <component :is="item.icon" theme="outline" size="16" />
                <span v-if="!mini" class="text-xs">{{ item.label }}</span>
            </div>
        </div>
        <div v-if="loading" class="absolute inset-0 w-full h-full bg-white flex items-center justify-center">
            <a-spin :size="24" />
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue';
import { Upload, Folder } from '@icon-park/vue-next';
import { getProductFilesUpload, getUploadImage } from '@/api';
import { Message } from '@arco-design/web-vue';
import UploadFile from '@/utils/Upload';

interface MenuItem {
    label: string;
    icon: any;
    action: string;
}

export default defineComponent({
    name: 'Hover',
    
    components: {
        'icon-park-upload': Upload,
        'icon-park-folder': Folder,
    },
    
    props: {
        menuItems: {
            type: Array as PropType<MenuItem[]>,
            default: () => []
        },
        accept: {
            type: String,
            default: 'image/*'
        },
        maxSelectCount: {
            type: Number,
            default: 1
        },
        isUpload: {
            type: Boolean,
            default: false
        },
        mini: {
            type: Boolean,
            default: false
        },
        isLimitSize: {
            type: Boolean,
            default: false
        },
        type: {
            type: String,
            default: 'image'
        },
        folder: {
            type: String,
            default: '5'
        }
    },
    
    emits: ['item-click', 'update:file', 'update:media', 'update:count', 'update:loading'],
    
    data() {
        return {
            loading: false,
            // 默认菜单项
            defaultMenuItems: [
                { label: 'Local file', icon: 'icon-park-upload', action: 'local' },
                { label: 'Media centre', icon: 'icon-park-folder', action: 'media' }
            ]
        }
    },
    
    computed: {
        // 计算实际使用的菜单项
        menuItemsToUse() {
            return this.menuItems.length > 0 ? this.menuItems : this.defaultMenuItems;
        }
    },
    
    methods: {
        handleItemClick(item: MenuItem, index: number) {
            // 发送基本点击事件，向后兼容
            this.$emit('item-click', { item, index });
            
            // 根据操作类型执行对应功能
            if (item.action === 'local') {
                this.handleLocalFile();
            } else if (item.action === 'media') {
                this.$emit('update:count', this.maxSelectCount);
                setTimeout(() => {
                    this.$emit('update:media', true);
                }, 100);
            }
        },
        
        handleLocalFile() {
            // 创建并触发文件选择输入
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = this.accept;
            input.onchange = async (e: Event) => {
                const target = e.target as HTMLInputElement;
                if (target.files && target.files.length > 0) {
                    const file = target.files[0];
                    if (this.isUpload) {
                        const temp = new Image();
                        temp.src = URL.createObjectURL(file);
                        try {
                            if (this.type === 'image') {
                                await new Promise((resolve, reject) => {
                                    temp.onload = () => {
                                        if (this.isLimitSize && (temp.width !== 600 || temp.height !== 600)) {
                                            Message.error('Dimensions: 600 x 600 px.');
                                            reject(new Error('Invalid image size'));
                                        } else {
                                            resolve(true);
                                        }
                                    };
                                    temp.onerror = () => {
                                        reject(new Error('Failed to load image'));
                                    };
                                });
                            }
                            
                            this.loading = true;
                            this.$emit('update:loading', true);
                            const formData = new FormData();
                            formData.append('file', file);
                            if (this.type === 'image') {
                                formData.append('width', String(temp.width));
                                formData.append('height', String(temp.height));
                            }
                            formData.append('folder_id', this.folder);
                            
                            if (this.type === 'image') {
                                try {
                                    const imageUrl = await UploadFile(file, 'image');
                                    console.log(imageUrl);
                                    this.$emit('update:file', { url: imageUrl, file });
                                } catch (error) {
                                    Message.error('Upload failed');
                                } finally {
                                    this.loading = false;
                                    this.$emit('update:loading', false);
                                    URL.revokeObjectURL(temp.src);
                                }
                            } else {
                                const res = await getProductFilesUpload(formData);
                                const result = res.data || {};
                                this.$emit('update:file', { id: result.material_id, url: config.global.static + result.url, file });
                            }
                        } catch (error) {
                            if (error.message !== 'Invalid image size') {
                                Message.error('Upload failed');
                            }
                            this.loading = false;
                            this.$emit('update:loading', false);
                            URL.revokeObjectURL(temp.src);
                        }
                    } else {
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            const url = e.target?.result as string;
                            // 将选择的文件信息返回给父组件
                            this.$emit('update:file', { url, file });
                        };
                        reader.readAsDataURL(file);
                    }

                }
            };
            input.click();
        }
    }
});
</script>